package com.ckv.qcm.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ckv.qcm.model.Session;
import com.ckv.qcm.model.Trainee;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class TestServlet
 */
public class SessionServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SessionServlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		processRequest(request, response);
	}
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
	{
		RequestDispatcher rd = null;
		String requestDispatcher = "";
		String ret = new String();
		try
		{
			HttpSession session = request.getSession();
			
			Trainee user = (Trainee)session.getAttribute("user");
			
			if(user != null)
			{
				ArrayList<Session> sessions = user.getCurrentSessions();
				
				for (Session sess : sessions)
				{
					sess.loadTest();
				}
				GsonBuilder builder = new GsonBuilder();
				builder.setDateFormat("dd/MM/yyyy");
				Gson gson = builder.create();
				ret = gson.toJson(sessions);
			}
			else
			{
//				requestDispatcher = "html/server_error.html";
//				rd = request.getRequestDispatcher(requestDispatcher);
//				rd.forward(request, response);
			}
			
			response.setContentType("text/html; charset=UTF-8");

			PrintWriter out = response.getWriter();
			out.print(ret);
			out.flush();
			out.close();
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
//			requestDispatcher = "html/server_error.html";
//			rd = request.getRequestDispatcher(requestDispatcher);
//			rd.forward(request, response);
		}
			
		
	}

}
